<template>
  <a-card>
    <!-- 查询   -->
    <a-form
        ref="searchFormRef"
        :model="search_form"
        @submit="handleSearchSubmit"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left">
      <a-row>
        <a-col :flex="1">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="车牌号" field="licensePlate">
                <a-input placeholder="请输入车牌号" v-model="search_form.licensePlate"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="品牌" field="brand">
                <a-input placeholder="请输入品牌" v-model="search_form.brand"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="状态" field="status">
                <a-select placeholder="请选择状态" v-model="search_form.status" allow-clear>
                  <a-option value="Z">正常</a-option>
                  <a-option value="B">保养中</a-option>
                  <a-option value="W">维修中</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-divider style="height: 84px" direction="vertical"/>
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search/>
              </template>
              查询
            </a-button>
            <a-button @click="$refs.searchFormRef.resetFields()">
              <template #icon>
                <icon-refresh/>
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider/>
      <!-- 添加操作   -->
      <a-row>
        <a-col :span="6" style="padding-bottom: 10px">
          <a-space>
            <a-button
                type="primary" shape="round" @click="addCarOpen">
              <template #icon>
                <icon-plus/>
              </template>
              <template #default>新增车辆</template>
            </a-button>
            <a-button shape="round">
              导出表格
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="12" class="mb-1"></a-col>
      </a-row>
    </a-form>
    <!-- 信息展示   -->
    <a-table :columns="columns" :data="cars"
             :pagination="pagination"
             @page-change="handlePaginationChange" style="height: 70vh">
      <template #licensePlate="{record,rowIndex}">
        <a-descriptions :column="1">
          <a-descriptions-item>
            {{ record.licensePlateWbxqy }}
          </a-descriptions-item>
          <a-descriptions-item>
            <a-avatar
                shape="square"
                :size="32">
              <img
                  alt="car image"
                  :src="record.imageUrlWbxqy"
              />
            </a-avatar>
          </a-descriptions-item>
        </a-descriptions>
      </template>
      <template #status="{record,rowIndex}">
        <a-tag v-if="record.statusWbxqy==='空闲'" style="border-radius: 20px; background-color: #87d068;color:white">
          空闲
        </a-tag>
        <a-tag v-else-if="record.statusWbxqy==='使用中'"
               style="border-radius: 20px; background-color: #108ee9;color:white">
          使用中
        </a-tag>
        <a-tag v-else-if="record.statusWbxqy==='维修中'"
               style="border-radius: 20px; background-color: #f50;color:white">
          维修中
        </a-tag>
      </template>
      <template #operations="{record,rowIndex}">
        <a-space>
          <a-button
              type="outline" @click="editCarOpen(record)">
            <template #icon>
              <icon-edit/>
            </template>
            编辑
          </a-button>
          <a-button
              type="outline" @click="addCarRecordOpen(record)">
            <template #icon>
              <icon-settings/>
            </template>
            添加记录
          </a-button>
          <a-button
              type="outline" @click="this.$router.push({ path: '/carRecord', query: { carIdWbxqy: record.carIdWbxqy } })">
            <template #icon>
              <icon-eye/>
            </template>
            查看记录
          </a-button>
        </a-space>
      </template>
    </a-table>
    <!-- 添加车辆对话框   -->
    <a-modal v-model:visible="showAddCarModal" title="添加车辆" @before-ok="addCarOk"
             @cancel="addCarCancel">
      <a-form ref="addCarFormRef" :model="addCarForm" :rules="rules">
        <a-form-item label="车牌号" field="licensePlateWbxqy">
          <a-input v-model="addCarForm.licensePlateWbxqy"/>
        </a-form-item>
        <a-form-item label="品牌" field="brandWbxqy">
          <a-input v-model="addCarForm.brandWbxqy"/>
        </a-form-item>
        <a-form-item label="型号" field="modelWbxqy">
          <a-input v-model="addCarForm.modelWbxqy"/>
        </a-form-item>
        <a-form-item label="状态" field="statusWbxqy">
          <a-select placeholder="请选择车辆状态" v-model="addCarForm.statusWbxqy" allow-clear>
            <a-option value="Z">正常</a-option>
            <a-option value="B">保养中</a-option>
            <a-option value="W">维修中</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="购买日期" field="purchaseDateWbxqy">
          <a-date-picker v-model="addCarForm.purchaseDateWbxqy"/>
        </a-form-item>
        <a-form-item label="车辆照片" field="imageUrlWbxqy">
          <a-space direction="vertical" :style="{ width: '100%' }">
            <a-upload
                :action="uploadUrl"
                :fileList="avatar ? [avatar] : []"
                :show-file-list="false"
                @change="onChange"
                @success="onSuccess"
            >
              <template #upload-button>
                <div
                    :class="`arco-upload-list-item${
            avatar && avatar.status === 'error' ? ' arco-upload-list-item-error' : ''
          }`"
                >
                  <div
                      class="arco-upload-list-picture custom-upload-avatar"
                      v-if="avatar && avatar.url"
                  >
                    <img :src="avatar.url"/>
                    <div class="arco-upload-list-picture-mask">
                      <IconEdit/>
                    </div>
                    <a-progress
                        v-if="avatar.status === 'uploading' && avatar.percent < 100"
                        :percent="avatar.percent"
                        type="circle"
                        size="mini"
                        :style="{
                position: 'absolute',
                left: '50%',
                top: '50%',
                transform: 'translateX(-50%) translateY(-50%)',
              }"
                    />
                  </div>
                  <div class="arco-upload-picture-card" v-else>
                    <div class="arco-upload-picture-card-text">
                      <IconPlus/>
                      <div style="margin-top: 10px; font-weight: 600">上传车辆照片</div>
                    </div>
                  </div>
                </div>
              </template>
            </a-upload>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 编辑车辆对话框   -->
    <a-modal v-model:visible="showEditCarModal" title="编辑车辆" @before-ok="editCarOk"
             @cancel="editCarCancel">
      <a-form ref="editCarFormRef" :model="editCarForm" :rules="rules">
        <a-form-item label="车牌号" field="licensePlateWbxqy">
          <a-input v-model="editCarForm.licensePlateWbxqy"/>
        </a-form-item>
        <a-form-item label="品牌" field="brandWbxqy">
          <a-input v-model="editCarForm.brandWbxqy"/>
        </a-form-item>
        <a-form-item label="型号" field="modelWbxqy">
          <a-input v-model="editCarForm.modelWbxqy"/>
        </a-form-item>
        <a-form-item label="状态" field="statusWbxqy">
          <a-select placeholder="请选择车辆状态" v-model="editCarForm.statusWbxqy" allow-clear>
            <a-option value="Z">正常</a-option>
            <a-option value="B">保养中</a-option>
            <a-option value="W">维修中</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="购买日期" field="purchaseDateWbxqy">
          <a-date-picker v-model="editCarForm.purchaseDateWbxqy"/>
        </a-form-item>
        <a-form-item label="车辆照片" field="imageUrlWbxqy">
          <a-space direction="vertical" :style="{ width: '100%' }">
            <a-upload
                :action="uploadUrl"
                :fileList="editAvatar ? [editAvatar] : []"
                :show-file-list="false"
                @change="onEditChange"
                @success="onEditSuccess"
            >
              <template #upload-button>
                <div
                    :class="`arco-upload-list-item${
            editAvatar && editAvatar.status === 'error' ? ' arco-upload-list-item-error' : ''
          }`"
                >
                  <div
                      class="arco-upload-list-picture custom-upload-avatar"
                      v-if="editAvatar && editAvatar.url"
                  >
                    <img :src="editAvatar.url"/>
                    <div class="arco-upload-list-picture-mask">
                      <IconEdit/>
                    </div>
                    <a-progress
                        v-if="editAvatar.status === 'uploading' && editAvatar.percent < 100"
                        :percent="editAvatar.percent"
                        type="circle"
                        size="mini"
                        :style="{
                position: 'absolute',
                left: '50%',
                top: '50%',
                transform: 'translateX(-50%) translateY(-50%)',
              }"
                    />
                  </div>
                  <div class="arco-upload-picture-card" v-else>
                    <div class="arco-upload-picture-card-text">
                      <IconPlus/>
                      <div style="margin-top: 10px; font-weight: 600">上传车辆照片</div>
                    </div>
                  </div>
                </div>
              </template>
            </a-upload>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 添加记录对话框 -->
    <a-modal v-model:visible="showAddCarRecordModal" title="添加记录" @before-ok="addCarRecordOk"
             @cancel="addCarRecordCancel">
      <a-form ref="addCarRecordFormRef" :model="addCarRecordForm" :rules="rules">
        <a-form-item label="车牌号" field="licensePlateWbxqy">
          <a-input v-model="addCarRecordForm.licensePlateWbxqy" disabled/>
        </a-form-item>
        <a-form-item label="记录日期" field="recordDateWbxqy">
          <a-date-picker v-model="addCarRecordForm.recordDateWbxqy" format="YYYY-MM-DD"/>
        </a-form-item>
        <a-form-item label="记录类型" field="recordCateWbxqy">
          <a-select v-model="addCarRecordForm.recordCateWbxqy" placeholder="请选择记录类型">
            <a-option value="W">维修</a-option>
            <a-option value="B">保养</a-option>
            <a-option value="J">检修</a-option>
            <a-option value="E">其他</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="详细描述" field="descriptionWbxqy">
          <a-input v-model="addCarRecordForm.descriptionWbxqy" type="text"/>
        </a-form-item>
        <a-form-item label="费用" field="costWbxqy">
          <a-input-number v-model="addCarRecordForm.costWbxqy" min="0"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import {
  ref,
  reactive
} from "vue";
import {getAllCars, updateCar, addCar} from "@/api/carMG";
import {IconEdit, IconPlus, IconSearch, IconRefresh, IconSettings, IconEye} from '@arco-design/web-vue/es/icon';
import {addCarRecord} from "@/api/carRecordMG";

const searchFormRef = ref(null);
const search_form = reactive({
  licensePlate: "",
  brand: "",
  status: ""
});
const columns = [{
  title: "车牌号",
  dataIndex: "licensePlateWbxqy",
  slotName: "licensePlate"
},
  {
    title: "品牌",
    dataIndex: "brandWbxqy"
  },
  {
    title: "型号",
    dataIndex: "modelWbxqy"
  },
  {
    title: "状态",
    dataIndex: "statusWbxqy",
    slotName: "status"
  },
  {
    title: "购买日期",
    dataIndex: "purchaseDateWbxqy"
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: '150',
    align: 'center',
    slotName: 'operations',
    fixed: 'right'
  }
];
const cars = ref([]);
const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10
});
const fetchData = async () => {
  const {current, pageSize} = pagination.value;
  const params = {
    page: current,
    pageSize,
    ...search_form,
  }
  await getAllCars(params).then(res => {
    console.log(res)
    cars.value = res.records
    pagination.value.total = res.total
  }).catch(err => {
    console.log("获取车辆列表失败", err)
  })
};
const handlePaginationChange = (current, pageSize) => {
  pagination.value.current = current;
  pagination.value.pageSize = pageSize;
  fetchData();
};
const handleSearchSubmit = async () => {
  pagination.current = 1;
  fetchData();
};

const showAddCarModal = ref(false);
const showEditCarModal = ref(false);
const addCarFormRef = ref(null);
const editCarFormRef = ref(null);
const addCarForm = reactive({
  licensePlateWbxqy: "",
  brandWbxqy: "",
  modelWbxqy: "",
  statusWbxqy: "",
  purchaseDateWbxqy: "",
  imageUrlWbxqy: ""
});
// 上传头像（编辑）
const editAvatar = ref();
const onEditChange = (_, currentFile) => {
  editAvatar.value = {
    ...currentFile,
  };
};
const onEditSuccess = (value) => {
  editCarForm.imageUrlWbxqy = value.response.url
}
const editCarForm = reactive({
  carIdWbxqy: "",
  licensePlateWbxqy: "",
  brandWbxqy: "",
  modelWbxqy: "",
  statusWbxqy: "",
  purchaseDateWbxqy: "",
  imageUrlWbxqy: ""
});
const rules = {
  licensePlateWbxqy: [{
    required: true,
    message: "请输入车牌号",
    trigger: "blur"
  }],
  brandWbxqy: [{
    required: true,
    message: "请输入品牌",
    trigger: "blur"
  }],
  modelWbxqy: [{
    required: true,
    message: "请输入型号",
    trigger: "blur"
  }],
  statusWbxqy: [{
    required: true,
    message: "请选择状态",
    trigger: "change"
  }],
  purchaseDateWbxqy: [{
    required: true,
    message: "请选择购买日期",
    trigger: "change"
  }]
};
const addCarOpen = () => {
  showAddCarModal.value = true;
};
const addCarCancel = () => {
  showAddCarModal.value = false;
};
const addCarOk = async () => {
  await addCar(addCarForm);
  showAddCarModal.value = false;
  await fetchData();
};

const editCarOpen = (record) => {
  Object.assign(editCarForm, record);
  showEditCarModal.value = true;
};
const editCarCancel = () => {
  showEditCarModal.value = false;
};
const editCarOk = async () => {
  await updateCar(editCarForm);
  showEditCarModal.value = false;
  await fetchData();
};

const avatar = ref(null);
const uploadUrl = 'http://localhost:9999/upload'; // 替换为你的上传URL
const onChange = (_, currentFile) => {
  avatar.value = {
    ...currentFile,
  };
};

const onSuccess = (value) => {
  addCarForm.imageUrlWbxqy = value.response.url
}
const showAddCarRecordModal = ref(false);
//  添加车辆记录
const addCarRecordForm = ref({
  carIdWbxqy: '',
  licensePlateWbxqy: '',
  recordDateWbxqy: '',
  recordCateWbxqy: '',
  descriptionWbxqy: '',
  costWbxqy: 0
});
const addCarRecordOpen = (record) => {
  showAddCarRecordModal.value = true;
  console.log(record)
  addCarRecordForm.value.carIdWbxqy = record.carIdWbxqy;
  addCarRecordForm.value.licensePlateWbxqy = record.licensePlateWbxqy;
};

const addCarRecordOk = async () => {
  await addCarRecord(addCarRecordForm.value);
  showAddCarRecordModal.value = false;
  loadCarRecords();
};

const addCarRecordCancel = () => {
  showAddCarRecordModal.value = false;
};
// 添加车辆维修/
fetchData();
</script>

<style scoped>
.custom-upload-avatar {
  position: relative;
  width: 128px;
  height: 128px;
}

.custom-upload-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.custom-upload-avatar .arco-upload-list-picture-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.3);
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  border-radius: 4px;
  transition: opacity 0.3s;
}

.custom-upload-avatar:hover .arco-upload-list-picture-mask {
  opacity: 1;
}
</style>
